package com.robot.common.utils;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;

import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import darabonba.core.RequestConfiguration;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 阿里云发送短信工具类
 */
@Slf4j
@Data
@Service
@ConfigurationProperties("aliyun.sms")
public class AliSmsUtils {

    /**
     * 阿里云短信服务AccessKey ID
     */
    private String accessKeyId;
    /**
     * 阿里云短信服务AccessKey Secret
     */
    private String accessKeySecret;
    /**
     * 阿里云短信签名，需要在官网申请
     */
    private String signName;
    /**
     * 阿里云短信模板ID，需要在官网申请
     */
    private String templateCode;
    /**
     * 短信验证码有效期，单位秒
     */
    private String expireTime;

    private String endpoint;



    public SendSmsResponse sendSms(String phone,String code) throws ExecutionException, InterruptedException {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride(endpoint))
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam("{\"code\":\"" + code + "\"}")
                .build();
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 获取结果（阻塞调用线程，直到异步调用完成）
        SendSmsResponse resp = response.get();
        client.close();
        return resp;
    }



}
